import { AnyObject } from "@/types";
import { HTTP_HEADERS_CONTENT_TYPE_JSON } from "./headers";
import { translateURL } from "@/utils";

class HttpService {
  constructor() {}
  /**
   * 请求方法
   * @param url
   * 请求参数
   * @param params
   */
  private request<T>(url: string, params?: AnyObject): Promise<T> {
    return new Promise((resolve, reject) => {
      fetch(url, {
        ...(params || {}),
        ...HTTP_HEADERS_CONTENT_TYPE_JSON.headers,
        mode: "cors",
      })
        .then(async (response) => {
          const res: T = await response.json();
          resolve(res);
        })
        .catch((error: any) => {
          reject(error);
        });
    });
  }
  public get<T>(url: string, params?: AnyObject): Promise<T> {
    return this.request<T>(translateURL(url, params||{}), { method: "GET" });
  }

  public post<T>(url: string, params?: AnyObject): Promise<T> {
    return this.request<T>(url, {
      body: JSON.stringify(params),
      method: "POST",
    });
  }
}

export default new HttpService();
